//
//  RechargeViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/8/30.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class RechargeViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var balanceMoneyLabel: UILabel!
    @IBOutlet weak var selectedAmountLabel: UILabel!
    
    @IBOutlet var confirmPaymentView: UIView!
    @IBOutlet var payTable: UITableView!
    
    var selectedAmount = "100.00"
    
    var dataSource = [Pay.RechargeOption.List]() {
        didSet {
            collectionView.reloadData()
        }
    }

    var paySwatchData = [Order.Pay.Payment(rawValue: 2),
                         Order.Pay.Payment(rawValue: 1)]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //监听支付状态
        addObserve()

        selectedAmountLabel.text = "100.00"
        
        makePayItems()
    }
    
    //请求付款项列表
    func makePayItems() {
        
        
        Pay.rechargeOption(success: { [weak self] data in
            if let data = data, let self = self {
                self.balanceMoneyLabel.text = data.balanceMoney
                self.dataSource = data.rechargeOptionList
            }
        }) { message in
            p(message)
        }
    }
    func addObserve () {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.payblock { [weak self] response in

                guard let payment = self?.selectedPayment() else {
                    return
                }
                
                switch payment {
                case .aliPay:
                    
                    //支付宝回调
                    if let value = response as? [AnyHashable : AnyObject]{
                        let code = value["resultStatus"] as? String
                        if code == "9000"{
                            self?.makePayItems()
                        } else {
                            XHProgressHUD.showError("你取消了支付")
                        }
                    }
                    
                case .wePay:
                    //微信回调
                    let model = response as! BaseResp
                    if model.errCode == -2 {
                        XHProgressHUD.showError("你已取消支付")
                    } else {
                        self?.makePayItems()
                    }
                    
                    break
                case .balance, .ticket:
                    break
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func showConfirmPaymentView(_ sender: UIButton) {
        confirmPaymentView.size.width = kScreenWidth
        confirmPaymentView.origin.y = view.frame.size.height
        view.addSubview(confirmPaymentView)

        UIView.animate(withDuration: 0.25) { [weak self] in
            if let self = self {
                let y = self.view.frame.size.height - self.confirmPaymentView.size.height
                self.confirmPaymentView.origin.y = y
            }
        }
    }
    
    @IBAction func closeConfirmPaymentView(_ sender: UIButton) {
        confirmPaymentView.removeFromSuperview()
    }
    
    @IBAction func confirmPay(_ sender: UIButton) {
        
        guard let p = selectedPayment() else {
            alert(message: "请选择支付方式")
            return
        }
        
        Pay.recharge(rechargeMoney: selectedAmount, payment: p, success: { data in
            if let payStr = data {
                switch p {
                case .aliPay:
                    Pay.zhifuPay(payStr: payStr.pay_str)
                case .wePay:
                    Pay.wechatPay(payStr: payStr.pay_str)
                case .balance, .ticket:
                    break
                }
            }
        }) { [weak self] message in
            self?.showError(message)
        }
    }
}

// MARK: - UICollectionViewDataSource

extension RechargeViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RechargeCollectionViewCell
        cell.layer.cornerRadius = 4
        
        cell.layer.masksToBounds = true
        cell.layer.borderWidth = 1
        
        cell.layer.borderColor = UIColor(red: 221.0/255.0, green: 221.0/255.0, blue: 221.0/255.0, alpha: 1.0).cgColor
        cell.moneyLabel.textColor = UIColor.black
        cell.layer.backgroundColor = UIColor.white.cgColor
        
        let item = dataSource[indexPath.row]
        
        cell.moneyLabel.text = item.optionName
        if item.amount == selectedAmount {
            cell.layer.borderColor = UIColor(red: 252.0/255.0, green: 166.0/255.0, blue: 72.0/255.0, alpha: 1.0).cgColor
            cell.moneyLabel.textColor = UIColor.white
            cell.layer.backgroundColor = UIColor(valueRGB: 0xFCA648, alpha: 1.0).cgColor
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
        
        return header
    }
    
    func selectedPayment() -> Order.Pay.Payment? {
        var payment: Order.Pay.Payment?
        for cell in payTable.visibleCells {
            if let cell = cell as? PayMethodCell {
                if cell.isSelected {
                    payment = cell.type
                }
            }
        }
        return payment
    }
}

// MARK: - UICollectionViewDelegate

extension RechargeViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let item = dataSource[indexPath.row]
        selectedAmount = item.amount
        selectedAmountLabel.text = item.optionName
        collectionView.reloadData()
    }
}

// MARK: - UITableViewDataSource

extension RechargeViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return paySwatchData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "payCell", for: indexPath)
        
        if let item = paySwatchData[indexPath.row], let cell = cell as? PayMethodCell {
            cell.type = item
        }
        return cell
    }
}

// MARK: - UITableViewDelegate

extension RechargeViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        for cell in tableView.visibleCells {
            if let cell = cell as? PayMethodCell {
                cell.setSelected(false, animated: true)
            }
        }
        if let cell = tableView.cellForRow(at: indexPath) as? PayMethodCell {
            cell.setSelected(true, animated: true)
        }
    }
}
